package dao

import (
	"flag"
	"fmt"
	"gitee.com/gopher2011/gva/server/util"
	"github.com/fsnotify/fsnotify"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/kotlin2018/mbt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"log"
	"os"
	"path"
	"path/filepath"
	"time"
)

var (
	Cfg Config
	RedisClient  *redis.Client
	Log    		 *zap.Logger      //日志记录器
	level 		 zapcore.Level
	Vp 			 *viper.Viper
)

const (
	ConfigEnv  string = "GVA_CONFIG"
	ConfigFile string = "./config.toml"
)

type Config struct {
	JWT        *JWT          `mapstructure:"jwt" json:"jwt" yaml:"jwt"`
	Zap        *Zap          `mapstructure:"zap" json:"zap" yaml:"zap"`
	Redis      *Redis        `mapstructure:"redis" json:"redis" yaml:"redis"`
	Email      *Email        `mapstructure:"email" json:"email" yaml:"email"`
	Casbin     *Casbin       `mapstructure:"casbin" json:"casbin" yaml:"casbin"`
	System     *system       `mapstructure:"system" json:"system" yaml:"system"`
	Captcha    *Captcha      `mapstructure:"captcha" json:"captcha" yaml:"captcha"`
	AutoCode   *Autocode     `mapstructure:"autoCode" json:"autoCode" yaml:"autoCode"`
	Local      *Local        `mapstructure:"local" json:"local" yaml:"local"`
	Qiniu      *Qiniu        `mapstructure:"qiniu" json:"qiniu" yaml:"qiniu"`
	AliyunOSS  *AliyunOSS    `mapstructure:"aliyun-oss" json:"aliyunOSS" yaml:"aliyun-oss"`
	TencentCOS *TencentCOS   `mapstructure:"tencent-cos" json:"tencentCOS" yaml:"tencent-cos"`
	Excel      *Excel        `mapstructure:"excel" json:"excel" yaml:"excel"`
	Timer      *Timer        `mapstructure:"timer" json:"timer" yaml:"timer"`
	Database   *mbt.Database //第一个数据库的配置项
}
// 将 ./config.yaml中的配置信息解析到config.go中的结构体上,参数 <path>是配置文件的路径
func initConfig(path ...string){
	var config string
	if len(path) == 0 {
		flag.StringVar(&config,"c","","choose config file")
		flag.Parse()
		if config == "" {// 优先级: 命令行 > 环境变量 > 默认值
			if configEnv := os.Getenv(ConfigEnv);configEnv == "" {
				config = ConfigFile
				fmt.Printf("您正在使用config的默认值,config的路径为%s\n", ConfigFile)
			}else {
				config = configEnv
				fmt.Printf("您正在使用GVA_Config的环境变量,config的路径为%s\n", config)
			}
		}else {
			fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
		}
	}else {
		config = path[0]
		fmt.Printf("您正在使用Viper()函数输入参数传递的值,config的路径为%v\n", config)
	}
	v := viper.New()
	v.SetConfigFile(config)
	if err := v.ReadInConfig();err !=nil {
		log.Println(fmt.Errorf("Fatal error config file : %s \n",err))
	}
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		log.Println("config file changed:",in.Name)
		if err := v.Unmarshal(&Cfg);err !=nil {
			log.Println(err)
		}
	})
	if err := v.Unmarshal(&Cfg);err !=nil {
		log.Println(err)
	}
	Vp = v
	Cfg.AutoCode.Root,_ = filepath.Abs("..")
}
func init(){
	initConfig()
	initZap()
	initDB()
	initRedis()
	initTimer()
}
func initRedis(){
	redisCfg := Cfg.Redis
	client := redis.NewClient(&redis.Options{
		Addr: redisCfg.Addr,
		Password: redisCfg.Password,// no password set
		DB: redisCfg.DB,// use default DB
	})
	pong,err := client.Ping().Result()
	if err != nil {
		Log.Error("redis connect ping failed, err:",zap.Any("err",err))
	}else {
		Log.Info("redis connect ping response:",zap.String("pong",pong))
		RedisClient = client
	}
}
func initZap(){
	// 判断是Director这个变量保存的文件夹是否存在
	if ok := util.PathExist(Cfg.Zap.Director); ok {
		fmt.Printf("创建 %v 文件夹\n", Cfg.Zap.Director)
		os.Mkdir(Cfg.Zap.Director, os.ModePerm)
	}
	// 初始化配置文件的Level
	switch Cfg.Zap.Level {
	case "debug":
		level = zap.DebugLevel
	case "info":
		level = zap.InfoLevel
	case "warn":
		level = zap.WarnLevel
	case "error":
		level = zap.ErrorLevel
	case "dpanic":
		level = zap.DPanicLevel
	case "panic":
		level = zap.PanicLevel
	case "fatal":
		level = zap.FatalLevel
	default:
		level = zap.InfoLevel
	}
	if level == zap.DebugLevel || level == zap.ErrorLevel {
		Log = zap.New(getEncoderCore(), zap.AddStacktrace(level))
	} else {
		Log = zap.New(getEncoderCore())
	}
	if Cfg.Zap.ShowLine { //显示日志行
		Log = Log.WithOptions(zap.AddCaller())
	}
}

// getEncoderConfig 获取 zapcore的编码器配置
func getEncoderConfig() zapcore.EncoderConfig {
	cfg := zapcore.EncoderConfig{ //定义了输出的样式，比如Key，调用者样式等
		//*Key：设置的是在结构化输出时，value对应的key
		MessageKey:     "message",
		LevelKey:       "level",
		TimeKey:        "time",
		NameKey:        "logger",
		CallerKey:      "caller",
		StacktraceKey:  Cfg.Zap.StacktraceKey,       //堆栈跟踪
		LineEnding:     zapcore.DefaultLineEnding,      //日志的结束符(换行符)
		EncodeLevel:    zapcore.LowercaseLevelEncoder,  //Level的输出样式，比如 大小写，颜色等
		EncodeTime:     CustomLoggerTimeFormat,         //日志时间的输出样式
		EncodeDuration: zapcore.SecondsDurationEncoder, //消耗时间的输出样式
		EncodeCaller:   zapcore.FullCallerEncoder,      //显示完整文件路径 (Caller的输出样式，比如 全名称，短名称)
	}
	switch {
	case Cfg.Zap.EncodeLevel == "LowercaseLevelEncoder": //小写编码器(默认)
		cfg.EncodeLevel = zapcore.LowercaseLevelEncoder
	case Cfg.Zap.EncodeLevel == "LowercaseColorLevelEncoder": //小写编码器带颜色
		cfg.EncodeLevel = zapcore.LowercaseColorLevelEncoder
	case Cfg.Zap.EncodeLevel == "CapitalLevelEncoder": //大写编码器
		cfg.EncodeLevel = zapcore.CapitalLevelEncoder
	case Cfg.Zap.EncodeLevel == "CapitalColorLevelEncoder": //大写编码器带颜色
		cfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
	default:
		cfg.EncodeLevel = zapcore.LowercaseLevelEncoder //默认:小写编码器
	}
	return cfg
}

// getEncoder 获取zapcore.Encoder(日志将以何种格式输出)
// 介绍博客: https://blog.csdn.net/C_jian/article/details/111315457
func getEncoder() zapcore.Encoder {
	if Cfg.Zap.Format == "json" { // https://www.jianshu.com/p/a342a20dc067
		// 将日志以json格式输出到具体的文件中
		return zapcore.NewJSONEncoder(getEncoderConfig()) //使用json编码器输出的日志是json格式,例如:{"level":"info","msg":"this will be logged"}
	}
	return zapcore.NewConsoleEncoder(getEncoderConfig()) //输出普通文本格式
}

// getEncoderCore 获取Encoder的zapcore.Core
// 详情: https://blog.csdn.net/jkwanga/article/details/107186653
func getEncoderCore() (core zapcore.Core) {
	//使用file-rotatelogs进行日志分割 ("github.com/lestrrat-go/file-rotatelogs")
	writer, err := util.GetWriteSyncer()
	if err != nil {
		fmt.Printf("对zap日志文件切割失败:%v", err.Error())
		return
	}
	return zapcore.NewCore(getEncoder(), writer, level)
}

// 自定义日志输出时间格式
func CustomLoggerTimeFormat(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format(Cfg.Zap.Prefix + "2006/01/02 - 15:04:05.000"))
}

func initDB() {
	engine := mbt.New(Cfg.Database)
	engine.Register(initMapper())
	engine.SetOutPut(initLogger(Cfg.Database.Logger.Path, Cfg.Database.Logger.MaxAge, Cfg.Database.Logger.Interval))
	engine.Run()
}
func initMapper() map[interface{}]interface{} {
	h := mbt.H{
		&CasbinRuleDao:            &CasbinRule{},            // casbin策略表
		&CustomerDao:              &Customer{},              //
		&FileDao:                  &File{},                  //
		&FileChunkDao:             &FileChunk{},             //
		&FileUploadAndDownloadDao: &FileUploadAndDownload{}, //
		&JwtBlackListDao:          &JwtBlackList{},          //
		&SimpleUploaderDao:        &SimpleUploader{},        //
		&SysApiDao:                &SysApi{},                //
		&SysAuthorityDao:          &SysAuthority{},          //
		&SysAuthorityMenuDao:      &SysAuthorityMenu{},      //
		&SysBaseMenuDao:           &SysBaseMenu{},           //
		&SysBaseMenuParameterDao:  &SysBaseMenuParameter{},  //
		&SysDataAuthorityIdDao:    &SysDataAuthorityId{},    //
		&SysDictionaryDao:         &SysDictionary{},         //
		&SysDictionaryDetailDao:   &SysDictionaryDetail{},   //
		&SysOperationRecordDao:    &SysOperationRecord{},    //
		&SysUserDao:               &SysUser{},               //
	}
	return h
}
func initLogger(logFilePath string, maxAge, interval int) io.Writer {
	/* 日志轮转相关函数
	WithLinkName() 	 为最新的日志建立软连接
	WithRotationTime()  设置日志分割的时间，隔多久分割一次
	WithMaxAge() 和 WithRotationCount() 二者只能设置一个
	WithMaxAge()  		 设置文件清理前的最长保存时间
	WithRotationCount() 设置文件清理前最多保存的个数
	*/
	// 下面配置日志每隔 interval 秒轮转一个新文件，保留最近 maxAge 秒的日志文件，多余的自动清理掉。
	writer, _ := rotatelogs.New(
		path.Join(logFilePath+"%Y-%m-%d.log"), //拼接成log文件名
		rotatelogs.WithLinkName(logFilePath),
		rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Hour),
		rotatelogs.WithRotationTime(time.Duration(interval)*time.Hour),
	)
	return writer
}
